from django import http
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.verifications import constant
from apps.verifications.constant import IMG_CODE_EXPIRE_TIME, SMS_CODE_EXPIRE_TIME, YUNTONGXUN_EXPIRE_TIME, \
    YUNTONGXUN_MODEL

from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from utils.response_code import RETCODE


class ImageCodeView(View):
    def get(self, request, uuid):
        text, image = captcha.generate_captcha()
        #链接数据库
        from django_redis import get_redis_connection
        #创建一个链接数据库实例对象
        redis_conn = get_redis_connection('code')
        #rides里面保存验证码并设置过期时间
        redis_conn.setex('img_%s'%uuid,IMG_CODE_EXPIRE_TIME , text)
        return HttpResponse(image, content_type='image/jpeg')
from django.http import HttpResponseBadRequest


class SMSCodeView(View):
    def get(self, request, mobile):
        params = request.GET
        uuid = params.get('image_code_id')
        text_cli = params.get('image_code')

        from django_redis import get_redis_connection
        try:
            redis_conn = get_redis_connection('code')
            text_server = redis_conn.get('img_%s'%uuid)
            if text_server is None:
                return HttpResponseBadRequest('验证码已过期')
            if text_server.decode().lower() != text_cli.lower():
                return HttpResponseBadRequest('验证码错误')
            #验证码没有问题也不再使用了，然后删除即可
            redis_conn.delete('img_%s'%uuid)
        except Exception as e:
            return HttpResponseBadRequest('数据库redis可能未打开')
        send_flag = params.get('send_flag')
        if send_flag:
            return JsonResponse({'code':RETCODE.THROTTLINGERR, 'error':'发送短信太快了'})


        from random import randint
        sms_code = '%06d'%randint(0,999999)
        import logging
        logger = logging.getLogger('django')
        logger.info(sms_code)

        # 1创建redis管道实例

        pl = redis_conn.pipeline()

        # 2 直接执行要执行的代码
        pl.setex('sms_%s'%mobile, SMS_CODE_EXPIRE_TIME, sms_code)
        pl.setex('send_flag_%s'%mobile,constant.SEND_FLAG_EXPIRE_TIME, 1)
        # 3 发送信息
        pl.execute()
#   调用celery任务。delay方法。有参数传参数
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code)
        return http.JsonResponse({'code':RETCODE.OK})







